import collections
class TreeNode(object):
    def __init__(self, x):
        self.val = x
        self.left = None
        self.right = None

class Codec:

    def serialize(self, root):
        """Encodes a tree to a single string.

        :type root: TreeNode
        :rtype: str
        """
        if not root:
            return ''
        now_layers = collections.deque([root])
        s = str(root.val) + ','
        flag = True
        while flag:
            next_layers = collections.deque()
            flag = False
            for item in now_layers:
                if item:
                    next_layers.append(item.left)
                    next_layers.append(item.right)
                    if item.left or item.right:
                        flag = True
            if flag:
                for item in next_layers:
                    if item:
                        s = s + str(item.val) + ','
                    else:
                        s = s + ' ' + ','
            now_layers = next_layers
        j = len(s) - 1
        while True:
            if s[j] == ' ' or s[j] == ',':
                j -= 1
            else:
                break
        return s[: j + 1]


    def deserialize(self, data):
        """Decodes your encoded data to tree.

        :type data: str
        :rtype: TreeNode
        """
        if not data:
            return None
        l = data.split(',')
        n = len(l)
        root = TreeNode(int(l[0]))
        index = 1
        now_layers = collections.deque([root])
        while index < n:
            next_layers = collections.deque()
            for item in now_layers:
                if l[index] == ' ':
                    item.left = None
                else:
                    item.left = TreeNode(int(l[index]))
                    next_layers.append(item.left)
                index += 1
                if index >= n:
                    break
                if l[index] == ' ':
                    item.right = None
                else:
                    item.right = TreeNode(int(l[index]))
                    next_layers.append(item.right)
                index += 1
                if index >= n:
                    break
            now_layers = next_layers
        return root





obj = Codec()
data = '1,2, ,3, ,4, ,5, , ,7'
root = obj.deserialize(data)
new_data = obj.serialize(root)
print(new_data)

